package com.wmh.baseservice.operationaid.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.operationaid.entity.ProductDetails;
import com.wmh.baseservice.operationaid.excel.ProductDetailsExecl;
import com.wmh.baseservice.operationaid.mapper.ProductDetailsMapper;
import com.wmh.baseservice.operationaid.pojo.vo.details.ProductDetailsCommitDataReqVO;
import com.wmh.baseservice.operationaid.pojo.vo.details.ProductDetailsListReqVO;
import com.wmh.baseservice.operationaid.pojo.vo.details.ProductDetailsPageReqVO;
import com.wmh.baseservice.operationaid.service.ProductDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 牛威龙
* @description 针对表【operation_aid_product_details】的数据库操作Service实现
* @createDate 2023-09-07 15:45:59
*/
@Service
@Slf4j
public class ProductDetailsServiceImpl extends ServiceImpl<ProductDetailsMapper, ProductDetails>
    implements ProductDetailsService {

    @Resource
    private ProductDetailsMapper productDetailsMapper;

    @Override
    public List<String> getStoreOptions() {
        return productDetailsMapper.getStoreOptions();
    }

    @Override
    public List<String> getDataCycleOptions() {
        return productDetailsMapper.getDataCycleOptions();
    }

    @Override
    public void commit(ProductDetailsCommitDataReqVO reqVO) {
        ProductDetails entity = baseMapper.selectOne(new LambdaQueryWrapperX<ProductDetails>()
                .eq(ProductDetails::getStoreName, reqVO.getStoreName())
                .eq(ProductDetails::getDataCycle, reqVO.getDataCycle())
                .eq(ProductDetails::getProductId, reqVO.getProductId()));
        // 更新
        if (!Objects.isNull(entity)) {
            BeanUtils.copyProperties(reqVO, entity);
            // 新增
        } else {
            entity = new ProductDetails();
            BeanUtils.copyProperties(reqVO, entity);
        }
        saveOrUpdate(entity);
    }

    @Override
    public List<ProductDetails> getProductDetailsList(ProductDetailsListReqVO reqVO) {
        LambdaQueryWrapperX<ProductDetails> wrapper = new LambdaQueryWrapperX<ProductDetails>();

        wrapper.eqIfPresent(ProductDetails::getProductId, reqVO.getProductId());
        wrapper.eq(StrUtil.isNotBlank(reqVO.getStoreName()), ProductDetails::getStoreName, reqVO.getStoreName());
        wrapper.eq(StrUtil.isNotBlank(reqVO.getDataCycle()), ProductDetails::getDataCycle, reqVO.getDataCycle());

        return productDetailsMapper.selectList(wrapper);
    }

    /**
     * 商品明细下载为 Excel 表格文件
     */
    @Override
    public void writeExcel(HttpServletResponse response, ProductDetailsPageReqVO reqVO) {
        ProductDetailsListReqVO productDetailsListReqVO = new ProductDetailsListReqVO();
        productDetailsListReqVO.setProductId(reqVO.getProductId());
        productDetailsListReqVO.setStoreName(reqVO.getStoreName());
        productDetailsListReqVO.setDataCycle(reqVO.getDataCycle());

        List<ProductDetails> productDetailsList = getProductDetailsList(productDetailsListReqVO);
        List<ProductDetailsExecl> data =  productDetailsList.stream()
                .map(e -> {
                    ProductDetailsExecl pe = new ProductDetailsExecl();
                    pe.setStoreName(e.getStoreName());
                    pe.setDateCycle(e.getDataCycle());
                    pe.setProductName(e.getProductName());
                    pe.setProductId(e.getProductId());
                    pe.setCategoryName(e.getCategoryName());
                    pe.setProductVisitorNums(e.getProductVisitorNums());
                    pe.setProductBrowseNums(e.getProductBrowseNums());
                    pe.setPaymentNums(e.getPaymentNums());
                    pe.setPaymentBuyerNums(e.getPaymentBuyerNums());
                    pe.setPaymentOrderNums(e.getPaymentOrderNums());
                    pe.setTransactionAmount(e.getTransactionAmount());
                    pe.setOrderNumberOfPeople(e.getOrderNumberOfPeople());
                    pe.setPaymentConversionRate(e.getPaymentConversionRate());
                    pe.setPlaceOrderRate(e.getPlaceOrderRate());
                    pe.setPayoutRate(e.getPayoutRate());
                    pe.setProductCollectionNums(e.getProductCollectionNums());
                    pe.setNumberOfGroupOrders(e.getNumberOfGroupOrders());
                    pe.setProductGroupNums(e.getProductGroupNums());
                    pe.setUvValue(e.getUvValue());
                    pe.setCustomerUnitPrice(e.getCustomerUnitPrice());
                    pe.setCollectionRate(e.getCollectionRate());
                    pe.setProductHelpPlatformRate(e.getProductHelpPlatformRate());
                    return pe;
                }).collect(Collectors.toList());

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String fileName ;
        try {
            fileName = URLEncoder.encode("fileName", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), ProductDetailsExecl.class).sheet("Sheet1").doWrite(data);
        } catch (IOException e) {
            log.error("下载商品明细数据异常: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }


}




